import React, { useState, useRef, useEffect } from 'react';
import { Card, Input, Button, List, Avatar, Typography, Space, Divider, Spin, Select, Tag, Tooltip, Radio, Drawer, Empty, message, Tabs, Collapse, Switch, Upload, Badge } from 'antd';
import { 
  SendOutlined, 
  UserOutlined, 
  RobotOutlined, 
  HistoryOutlined, 
  SaveOutlined, 
  DeleteOutlined, 
  CopyOutlined, 
  LoadingOutlined, 
  SettingOutlined,
  FileTextOutlined,
  DatabaseOutlined,
  PlusOutlined,
  InfoCircleOutlined,
  ApiOutlined,
  GlobalOutlined,
  LinkOutlined,
  FileAddOutlined,
  UploadOutlined,
  QuestionCircleOutlined,
  PaperClipOutlined,
  ClearOutlined,
  SyncOutlined
} from '@ant-design/icons';
import { theme } from 'antd';
import { UploadFile } from 'antd/lib/upload/interface';
import { useModelsStore, Model } from '../../stores/modelsStore';

const { Text, Paragraph, Title } = Typography;
const { Option } = Select;
const { TabPane } = Tabs;
const { Panel } = Collapse;

interface ChatMessage {
  id: string;
  content: string;
  role: 'user' | 'assistant' | 'system';
  timestamp: Date;
  metadata?: {
    sources?: {
      title: string;
      url?: string;
      content?: string;
    }[];
    tokens?: number;
    processingTime?: number;
    model?: string;
  };
}

interface ChatSession {
  id: string;
  title: string;
  createdAt: Date;
  updatedAt: Date;
  messages: ChatMessage[];
}

const ChatInterface: React.FC = () => {
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [inputValue, setInputValue] = useState('');
  const [isTyping, setIsTyping] = useState(false);
  const [selectedModel, setSelectedModel] = useState<Model | null>(null);
  const [historyDrawerVisible, setHistoryDrawerVisible] = useState(false);
  const [settingsDrawerVisible, setSettingsDrawerVisible] = useState(false);
  const [chatSessions, setChatSessions] = useState<ChatSession[]>([]);
  const [currentSessionId, setCurrentSessionId] = useState<string | null>(null);
  const [uploadedFiles, setUploadedFiles] = useState<UploadFile[]>([]);
  const [useKnowledgeBase, setUseKnowledgeBase] = useState(true);
  const [selectedKnowledgeSources, setSelectedKnowledgeSources] = useState<string[]>([]);
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const { token } = theme.useToken();
  const { llmModels, activeLlm, fetchModels } = useModelsStore();
  
  // 初始化时加载模型
  useEffect(() => {
    setIsTyping(true);
    fetchModels().then(() => {
      setIsTyping(false);
    });
    
    // 尝试恢复之前的知识库设置
    try {
      const savedKnowledgeBaseEnabled = localStorage.getItem('ai_assistant_knowledge_base_enabled');
      if (savedKnowledgeBaseEnabled !== null) {
        setUseKnowledgeBase(JSON.parse(savedKnowledgeBaseEnabled));
        console.log('已加载知识库启用状态:', JSON.parse(savedKnowledgeBaseEnabled));
      }
      
      const savedKnowledgeSources = localStorage.getItem('ai_assistant_knowledge_base_sources');
      if (savedKnowledgeSources) {
        setSelectedKnowledgeSources(JSON.parse(savedKnowledgeSources));
        console.log('已加载知识库来源:', JSON.parse(savedKnowledgeSources));
      }
    } catch (error) {
      console.error('加载知识库设置失败:', error);
    }
  }, [fetchModels]);
  
  // 当模型列表更新时，自动选择活跃模型
  useEffect(() => {
    if (llmModels.length > 0 && activeLlm) {
      const activeModel = llmModels.find(model => model.id === activeLlm);
      if (activeModel) {
        setSelectedModel(activeModel);
      } else if (!selectedModel) {
        // 如果没有活跃模型但有可用模型，选择第一个
        setSelectedModel(llmModels[0]);
      }
    }
  }, [llmModels, activeLlm, selectedModel]);
  
  // 添加事件监听，响应模型状态变化
  useEffect(() => {
    // 监听LLM模型变更
    const handleLlmModelChanged = (event: CustomEvent) => {
      console.log('LLM模型已更改:', event.detail);
      if (event.detail && event.detail.modelId) {
        const model = llmModels.find(m => m.id === event.detail.modelId);
        if (model) {
          setSelectedModel(model);
          console.log('ChatInterface已更新选中的模型为:', model.name);
        }
      }
    };
    
    // 监听模型刷新完成事件
    const handleModelRefreshComplete = (event: CustomEvent) => {
      console.log('模型刷新完成，ChatInterface正在更新状态...');
      if (event.detail && event.detail.activeLlm) {
        const model = llmModels.find(m => m.id === event.detail.activeLlm);
        if (model) {
          setSelectedModel(model);
          console.log('已更新为活跃模型:', model.name);
        } else {
          console.log('找不到匹配的活跃模型，将尝试使用第一个可用模型');
          if (llmModels.length > 0) {
            setSelectedModel(llmModels[0]);
          }
        }
      }
    };
    
    // 添加事件监听器
    document.addEventListener('llm-model-changed', handleLlmModelChanged as EventListener);
    document.addEventListener('models-refresh-complete', handleModelRefreshComplete as EventListener);
    
    // 移除事件监听器
    return () => {
      document.removeEventListener('llm-model-changed', handleLlmModelChanged as EventListener);
      document.removeEventListener('models-refresh-complete', handleModelRefreshComplete as EventListener);
    };
  }, [llmModels]);
  
  // 初始化一些示例聊天记录
  useEffect(() => {
    const sampleSessions: ChatSession[] = [
      {
        id: 'session-1',
        title: '关于产品功能的咨询',
        createdAt: new Date(Date.now() - 86400000 * 3),
        updatedAt: new Date(Date.now() - 86400000 * 3),
        messages: [
          {
            id: 'msg-1',
            content: '你好，我想了解一下你们的产品有哪些核心功能？',
            role: 'user',
            timestamp: new Date(Date.now() - 86400000 * 3)
          },
          {
            id: 'msg-2',
            content: '我们的知识库系统主要有以下核心功能：\n\n1. **文档管理**：支持上传、分类和版本控制各类文档\n2. **智能检索**：基于语义的文档检索，而不仅仅是关键词匹配\n3. **RAG流程编排**：可视化配置检索增强生成流程\n4. **多模型支持**：集成多种大语言模型，包括GPT-4、Claude等\n5. **权限管理**：细粒度的用户权限控制\n6. **审计日志**：完整记录系统操作，支持合规需求\n\n您对哪方面功能特别感兴趣？我可以提供更详细的介绍。',
            role: 'assistant',
            timestamp: new Date(Date.now() - 86400000 * 3),
            metadata: {
              sources: [
                { title: '产品功能介绍文档', url: '#' },
                { title: '系统架构白皮书', url: '#' }
              ],
              tokens: 256,
              processingTime: 1.2,
              model: 'gpt-4'
            }
          }
        ]
      },
      {
        id: 'session-2',
        title: '技术架构咨询',
        createdAt: new Date(Date.now() - 86400000 * 1),
        updatedAt: new Date(Date.now() - 86400000 * 1),
        messages: [
          {
            id: 'msg-3',
            content: '你们的系统架构是怎样的？可以支持私有化部署吗？',
            role: 'user',
            timestamp: new Date(Date.now() - 86400000 * 1)
          },
          {
            id: 'msg-4',
            content: '我们的系统采用微服务架构，主要组件包括：\n\n- 前端界面：React + TypeScript\n- 后端API：Node.js/Express 或 Python/FastAPI\n- 向量数据库：支持Milvus、Pinecone等\n- 文档处理服务：支持多种格式转换和索引\n- 模型协调服务：管理与各LLM API的交互\n\n关于部署方式，我们支持：\n\n1. **SaaS**：直接使用我们云端托管的服务\n2. **私有化部署**：可部署在您的内部服务器或私有云环境\n3. **混合模式**：核心数据本地存储，可选择性使用云服务\n\n私有化部署支持Docker容器和Kubernetes编排，可以根据您的基础设施需求进行定制。我们也提供完整的部署文档和技术支持。',
            role: 'assistant',
            timestamp: new Date(Date.now() - 86400000 * 1),
            metadata: {
              sources: [
                { title: '系统架构文档', url: '#' },
                { title: '部署指南', url: '#' }
              ],
              tokens: 320,
              processingTime: 1.5,
              model: 'gpt-4'
            }
          }
        ]
      }
    ];
    
    setChatSessions(sampleSessions);
  }, []);
  
  useEffect(() => {
    scrollToBottom();
  }, [messages]);
  
  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };
  
  const handleKnowledgeBaseChange = (checked: boolean) => {
    setUseKnowledgeBase(checked);
    try {
      localStorage.setItem('ai_assistant_knowledge_base_enabled', JSON.stringify(checked));
      console.log('已保存知识库启用状态:', checked);
    } catch (error) {
      console.error('保存知识库启用状态失败:', error);
    }
  };

  const handleKnowledgeSourcesChange = (sources: string[]) => {
    setSelectedKnowledgeSources(sources);
    try {
      localStorage.setItem('ai_assistant_knowledge_base_sources', JSON.stringify(sources));
      console.log('已保存知识库来源:', sources);
    } catch (error) {
      console.error('保存知识库来源失败:', error);
    }
  };
  
  // 添加同步模型状态函数
  const syncModelState = () => {
    console.log('手动同步模型状态...');
    if (activeLlm) {
      const activeModel = llmModels.find(model => model.id === activeLlm);
      if (activeModel) {
        setSelectedModel(activeModel);
        console.log('已同步到活跃模型:', activeModel.name);
        return;
      }
    }
    
    // 如果没有找到活跃模型，但有可用模型，选择第一个
    if (llmModels.length > 0) {
      setSelectedModel(llmModels[0]);
      console.log('找不到活跃模型，已选择第一个可用模型:', llmModels[0].name);
    } else {
      console.log('没有可用的语言模型');
    }
  };
  
  // 当渲染模型选择UI时，如果没有选中模型但发现有活跃模型，显示同步按钮
  const renderModelSelection = () => {
    if (selectedModel) {
      return (
        <Tag color="blue" icon={<ApiOutlined />}>
          {selectedModel.name} ({selectedModel.provider})
        </Tag>
      );
    } else if (isTyping) {
      return <Tag icon={<LoadingOutlined />}>加载模型中...</Tag>;
    } else {
      return (
        <Tag color="error" onClick={syncModelState} style={{ cursor: 'pointer' }}>
          未检测到已启用的模型，点击同步
        </Tag>
      );
    }
  };
  
  const handleSend = async () => {
    if (!inputValue.trim()) return;
    
    // 如果没有选择模型，尝试自动选择
    if (!selectedModel) {
      if (activeLlm) {
        const activeModel = llmModels.find(model => model.id === activeLlm);
        if (activeModel) {
          setSelectedModel(activeModel);
        } else if (llmModels.length > 0) {
          setSelectedModel(llmModels[0]);
        } else {
          message.error('请在模型中心启用至少一个语言模型');
          return;
        }
      } else if (llmModels.length > 0) {
        const activeModel = llmModels.find(model => model.isActive);
        if (activeModel) {
          setSelectedModel(activeModel);
        } else {
          setSelectedModel(llmModels[0]);
        }
      } else {
        message.error('无可用模型，请前往模型中心启用至少一个语言模型');
        return;
      }
    }
    
    // 添加用户消息
    const userMessage: ChatMessage = {
      id: `msg-${Date.now()}`,
      content: inputValue,
      role: 'user',
      timestamp: new Date()
    };
    
    setMessages(prev => [...prev, userMessage]);
    setInputValue('');
    setIsTyping(true);
    
    try {
      // 获取当前会话的历史消息（最多4条）
      const recentMessages = currentSessionId ? 
        chatSessions
          .find(s => s.id === currentSessionId)?.messages
          .slice(-4) || [] 
        : [];
      
      // 转换为Ollama API格式的消息
      const historyMessages = recentMessages.map(msg => ({
        role: msg.role,
        content: msg.content
      }));
      
      // 准备聊天消息历史
      const chatMessages = [
        { role: "system", content: "你是一个AI助手，基于提供的上下文回答用户问题" },
        ...historyMessages,
        { role: "user", content: inputValue }
      ];
      
      // 确定模型名称（Ollama模型使用名称，其他模型使用ID）
      const modelName = selectedModel?.provider === 'Ollama' 
        ? selectedModel.name.split('/').pop() // 提取Ollama模型实际名称
        : selectedModel?.id;
      
      console.log('使用模型:', modelName, '类型:', selectedModel?.provider);
      
      // 判断是否为Ollama模型
      const isOllamaModel = selectedModel?.provider === 'Ollama';
      
      if (isOllamaModel) {
        // 获取Ollama服务器地址
        const ollamaServer = localStorage.getItem('ollamaServer') || 'http://localhost:11434';
        console.log('连接Ollama服务器:', ollamaServer);
        
        // 准备Ollama请求数据
        const ollamaRequestData = {
          model: modelName,
          messages: chatMessages,
          stream: false, // 非流式响应，简化处理
          options: {
            temperature: 0.7,
            top_p: 0.9,
            top_k: 40
          }
        };
        
        console.log('发送Ollama请求:', ollamaRequestData);
        
        try {
          // 调用Ollama API
          const response = await fetch(`${ollamaServer}/api/chat`, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify(ollamaRequestData)
          });
          
          if (!response.ok) {
            throw new Error(`Ollama API错误: ${response.status} ${response.statusText}`);
          }
          
          // 解析Ollama响应
          const responseData = await response.json();
          console.log('Ollama响应:', responseData);
          
          // 添加AI助手回复
          const assistantMessage: ChatMessage = {
            id: `msg-${Date.now() + 1}`,
            content: responseData.message?.content || "抱歉，我无法生成回复。",
            role: 'assistant',
            timestamp: new Date(),
            metadata: {
              tokens: responseData.eval_count || 0,
              processingTime: responseData.total_duration ? responseData.total_duration / 1000000000 : 0, // 转换为秒
              model: selectedModel?.name
            }
          };
          
          setMessages(prev => [...prev, assistantMessage]);
          
          // 处理会话管理
          if (!currentSessionId) {
            // 创建新会话
            const newSession: ChatSession = {
              id: `session-${Date.now()}`,
              title: userMessage.content.substring(0, 30) + (userMessage.content.length > 30 ? '...' : ''),
              createdAt: new Date(),
              updatedAt: new Date(),
              messages: [userMessage, assistantMessage]
            };
            
            setChatSessions(prev => [newSession, ...prev]);
            setCurrentSessionId(newSession.id);
            message.success('已创建新的对话');
          } else {
            // 更新当前会话
            setChatSessions(prev => prev.map(session => 
              session.id === currentSessionId 
                ? { 
                    ...session, 
                    updatedAt: new Date(),
                    messages: [...session.messages, userMessage, assistantMessage]
                  } 
                : session
            ));
          }
        } catch (error) {
          console.error('Ollama API调用失败:', error);
          
          // 显示错误消息
          const errorMessage: ChatMessage = {
            id: `msg-${Date.now() + 1}`,
            content: `调用Ollama模型失败: ${error instanceof Error ? error.message : '未知错误'}。请确保Ollama服务器已启动，并已安装需要的模型。`,
            role: 'assistant',
            timestamp: new Date()
          };
          
          setMessages(prev => [...prev, errorMessage]);
          message.error('Ollama模型调用失败，请检查服务器状态');
        }
      } else {
        // 对于非Ollama模型，使用原有的模拟回复逻辑
        // 模拟API请求延迟
        setTimeout(() => {
          // 添加AI助手回复
          let assistantContent = '';
          let metadataSources = [];
          
          // 根据问题生成不同的模拟回复
          if (inputValue.toLowerCase().includes('价格') || inputValue.toLowerCase().includes('费用')) {
            assistantContent = "我们提供多种价格方案，从基础版到企业版：\n\n**基础版**：每月¥2,999，支持最多10个用户，100GB存储空间\n**专业版**：每月¥7,999，支持最多50个用户，500GB存储空间\n**企业版**：每月¥19,999，支持无限用户，2TB存储空间，专属技术支持\n\n所有版本都包含核心功能，高级版本增加了更多企业级功能和更高的服务等级。我们也提供私有化部署定制报价，您可以联系销售团队获取更详细的信息。";
            metadataSources = [{ title: '产品价格方案', url: '#' }];
          } else if (inputValue.toLowerCase().includes('安全') || inputValue.toLowerCase().includes('隐私')) {
            assistantContent = "我们非常重视数据安全和隐私保护，系统采取了多层次的安全措施：\n\n1. **数据加密**：所有数据传输采用TLS 1.3加密，存储采用AES-256加密\n2. **访问控制**：基于角色的细粒度权限管理，支持多因素认证\n3. **合规性**：符合GDPR、SOC 2、ISO 27001等标准\n4. **数据隔离**：客户数据严格隔离，私有化部署可确保数据不出企业内网\n5. **审计日志**：所有操作留有可追溯的审计记录\n\n对于特别敏感的行业，我们还提供定制化的安全解决方案，可以与您的安全团队深入讨论具体需求。";
            metadataSources = [
              { title: '安全白皮书', url: '#' },
              { title: '隐私政策', url: '#' }
            ];
          } else if (inputValue.toLowerCase().includes('demo') || inputValue.toLowerCase().includes('演示')) {
            assistantContent = "很高兴您对演示感兴趣！我们提供多种方式了解产品：\n\n1. **在线Demo**：您可以访问我们的演示环境，无需注册即可体验核心功能\n2. **预约演示**：由我们的产品专家进行1对1详细演示，针对您的具体需求进行讲解\n3. **试用账号**：申请14天全功能试用账号，体验完整产品功能\n\n您更倾向于哪种方式？我可以帮您安排。";
            metadataSources = [{ title: '产品演示预约', url: '#' }];
          } else {
            assistantContent = `感谢您的问题。基于您提到的"${inputValue.substring(0, 20)}..."，我建议您可以了解我们的知识库解决方案，它能帮助企业构建智能化的信息管理系统。\n\n我们的系统通过先进的RAG技术，将企业内部文档与大语言模型结合，提供精准的信息检索和问答服务。系统特点包括：\n\n1. 支持多种文档格式的智能处理\n2. 自定义知识图谱构建\n3. 精确的相关性搜索\n4. 便捷的流程配置工具\n\n您有任何特定方面的问题，我都可以为您提供更详细的信息。`;
            metadataSources = [
              { title: '产品介绍', url: '#' },
              { title: '技术白皮书', url: '#' }
            ];
          }
          
          const assistantMessage: ChatMessage = {
            id: `msg-${Date.now() + 1}`,
            content: assistantContent,
            role: 'assistant',
            timestamp: new Date(),
            metadata: {
              sources: metadataSources,
              tokens: Math.floor(Math.random() * 200) + 100,
              processingTime: Math.random() * 2 + 0.5,
              model: selectedModel?.id
            }
          };
          
          setMessages(prev => [...prev, assistantMessage]);
          
          // 如果这是新对话的第一条消息，创建新会话
          if (!currentSessionId) {
            const newSession: ChatSession = {
              id: `session-${Date.now()}`,
              title: userMessage.content.substring(0, 30) + (userMessage.content.length > 30 ? '...' : ''),
              createdAt: new Date(),
              updatedAt: new Date(),
              messages: [userMessage, assistantMessage]
            };
            
            setChatSessions(prev => [newSession, ...prev]);
            setCurrentSessionId(newSession.id);
            message.success('已创建新的对话');
          } else {
            // 更新当前会话
            setChatSessions(prev => prev.map(session => 
              session.id === currentSessionId 
                ? { 
                    ...session, 
                    updatedAt: new Date(),
                    messages: [...session.messages, userMessage, assistantMessage]
                  } 
                : session
            ));
          }
        }, 1500);
      }
    } catch (error) {
      console.error('发送消息出错:', error);
      setIsTyping(false);
      message.error('发送消息失败，请重试');
    } finally {
      setIsTyping(false);
    }
  };
  
  const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSend();
    }
  };
  
  const handleClearChat = () => {
    setMessages([]);
    setCurrentSessionId(null);
  };
  
  const loadChatSession = (sessionId: string) => {
    const session = chatSessions.find(s => s.id === sessionId);
    if (session) {
      setMessages(session.messages);
      setCurrentSessionId(session.id);
      setHistoryDrawerVisible(false);
      message.success(`已加载对话: ${session.title}`);
    }
  };
  
  const deleteChatSession = (sessionId: string, e: React.MouseEvent) => {
    e.stopPropagation();
    setChatSessions(prev => prev.filter(s => s.id !== sessionId));
    if (currentSessionId === sessionId) {
      setMessages([]);
      setCurrentSessionId(null);
    }
    message.success('已删除对话');
  };
  
  const copyMessageContent = async (content: string) => {
    try {
      await navigator.clipboard.writeText(content);
      message.success('已复制到剪贴板');
    } catch (err) {
      console.error('复制失败:', err);
      message.error('复制失败');
    }
  };
  
  // 渲染消息
  const renderMessage = (msg: ChatMessage) => {
    const isUser = msg.role === 'user';
    
    return (
      <List.Item key={msg.id} style={{ 
        padding: '12px 24px',
        backgroundColor: isUser ? token.colorBgContainer : token.colorFillQuaternary,
        marginBottom: '8px',
        borderRadius: '8px'
      }}>
        <List.Item.Meta
          avatar={
            <Avatar 
              icon={isUser ? <UserOutlined /> : <RobotOutlined />} 
              style={{ 
                backgroundColor: isUser ? token.colorPrimary : '#52c41a',
                marginTop: '4px'
              }}
            />
          }
          title={
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <Text strong>{isUser ? '你' : 'AI助手'}</Text>
              <Space>
                {!isUser && msg.metadata?.model && (
                  <Tag color="blue">模型: {msg.metadata.model}</Tag>
                )}
                {!isUser && (msg.metadata?.processingTime || msg.metadata?.tokens) && (
                  <Text type="secondary" style={{ fontSize: 12 }}>
                    {msg.metadata.tokens && `${msg.metadata.tokens}个Token`}
                    {msg.metadata.processingTime && msg.metadata.tokens && ' | '}
                    {msg.metadata.processingTime && `${msg.metadata.processingTime.toFixed(2)}秒`}
                  </Text>
                )}
                <Button 
                  type="text" 
                  icon={<CopyOutlined />} 
                  onClick={() => copyMessageContent(msg.content)}
                  size="small"
                />
              </Space>
            </div>
          }
          description={
            <div>
              <div style={{ 
                whiteSpace: 'pre-wrap',
                wordBreak: 'break-word'
              }}>
                {msg.content}
              </div>
              
              {!isUser && msg.metadata?.sources && msg.metadata.sources.length > 0 && (
                <div style={{ marginTop: 8 }}>
                  <Text type="secondary" style={{ fontSize: 12 }}>参考来源:</Text>
                  <ul style={{ margin: '4px 0', paddingLeft: 20 }}>
                    {msg.metadata.sources.map((source, index) => (
                      <li key={index}>
                        {source.url ? (
                          <a href={source.url} target="_blank" rel="noopener noreferrer">
                            {source.title}
                          </a>
                        ) : (
                          <Text>{source.title}</Text>
                        )}
                      </li>
                    ))}
                  </ul>
                </div>
              )}
            </div>
          }
        />
      </List.Item>
    );
  };
  
  // 渲染历史对话抽屉
  const renderHistoryDrawer = () => {
    return (
      <Drawer
        title="对话历史"
        placement="left"
        width={320}
        onClose={() => setHistoryDrawerVisible(false)}
        open={historyDrawerVisible}
        extra={
          <Button 
            icon={<PlusOutlined />} 
            type="primary"
            onClick={() => {
              setMessages([]);
              setCurrentSessionId(null);
              setHistoryDrawerVisible(false);
            }}
          >
            新对话
          </Button>
        }
      >
        {chatSessions.length === 0 ? (
          <Empty description="暂无对话历史" />
        ) : (
          <List
            dataSource={chatSessions.sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime())}
            renderItem={session => (
              <List.Item
                style={{ 
                  cursor: 'pointer',
                  backgroundColor: session.id === currentSessionId ? token.colorBgTextHover : 'transparent',
                  padding: '8px 12px',
                  borderRadius: '4px',
                  marginBottom: '4px'
                }}
                onClick={() => loadChatSession(session.id)}
                actions={[
                  <Button
                    key="delete"
                    type="text"
                    danger
                    icon={<DeleteOutlined />}
                    onClick={(e) => deleteChatSession(session.id, e)}
                  />
                ]}
              >
                <List.Item.Meta
                  title={<Text ellipsis>{session.title}</Text>}
                  description={
                    <Text type="secondary" style={{ fontSize: '12px' }}>
                      {session.messages.length}条消息 · {new Date(session.updatedAt).toLocaleDateString()}
                    </Text>
                  }
                />
              </List.Item>
            )}
          />
        )}
      </Drawer>
    );
  };
  
  // 渲染设置抽屉
  const renderSettingsDrawer = () => {
    return (
      <Drawer
        title="对话设置"
        placement="right"
        onClose={() => setSettingsDrawerVisible(false)}
        open={settingsDrawerVisible}
        width={400}
      >
        <Space direction="vertical" style={{ width: '100%' }} size="large">
          <div>
            <Title level={5}>模型选择</Title>
            <Select
              style={{ width: '100%' }}
              placeholder="选择语言模型"
              value={selectedModel?.id}
              onChange={(modelId) => {
                const newModel = llmModels.find(m => m.id === modelId);
                if (newModel) {
                  setSelectedModel(newModel);
                  // 通知模型变更
                  const event = new CustomEvent('chat-model-changed', {
                    detail: { modelId, modelName: newModel.name }
                  });
                  document.dispatchEvent(event);
                }
              }}
              loading={isTyping}
            >
              {llmModels.map(model => (
                <Option key={model.id} value={model.id}>
                  <Space>
                    <span>{model.name}</span>
                    {model.provider && <Tag>{model.provider}</Tag>}
                    {model.isActive && <Badge status="success" text="当前活跃" />}
                  </Space>
                </Option>
              ))}
            </Select>
            
            {/* Ollama连接状态信息 */}
            {selectedModel?.provider === 'Ollama' && (
              <div style={{ marginTop: 12, padding: 12, backgroundColor: '#f6f6f6', borderRadius: 6 }}>
                <Space direction="vertical" style={{ width: '100%' }}>
                  <Space>
                    <ApiOutlined />
                    <Text strong>Ollama连接信息</Text>
                  </Space>
                  <div>
                    <Text>服务器地址: </Text>
                    <Text code>{localStorage.getItem('ollamaServer') || 'http://localhost:11434'}</Text>
                  </div>
                  <Space>
                    <Button 
                      size="small" 
                      type="primary"
                      onClick={() => {
                        // 打开模型中心的Ollama配置
                        message.info('请在模型中心配置Ollama服务器');
                      }}
                    >
                      修改配置
                    </Button>
                    <Button 
                      size="small"
                      onClick={async () => {
                        try {
                          const ollamaServer = localStorage.getItem('ollamaServer') || 'http://localhost:11434';
                          const response = await fetch(`${ollamaServer}/api/version`);
                          if (response.ok) {
                            const data = await response.json();
                            message.success(`Ollama服务器连接成功，版本: ${data.version}`);
                          } else {
                            message.error('Ollama服务器连接失败');
                          }
                        } catch (error) {
                          message.error('Ollama服务器连接失败');
                          console.error('连接测试失败:', error);
                        }
                      }}
                    >
                      测试连接
                    </Button>
                  </Space>
                </Space>
              </div>
            )}
            
            <Divider />
          </div>
          
          <div>
            <Title level={5}>知识库设置</Title>
            <Space direction="vertical" style={{ width: '100%' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <Text>启用知识库</Text>
                <Switch 
                  checked={useKnowledgeBase}
                  onChange={handleKnowledgeBaseChange}
                />
              </div>
              
              {useKnowledgeBase && (
                <>
                  <Text type="secondary">选择知识库来源</Text>
                  <Select
                    mode="multiple"
                    style={{ width: '100%' }}
                    placeholder="选择知识库来源（可多选）"
                    value={selectedKnowledgeSources}
                    onChange={handleKnowledgeSourcesChange}
                    options={[
                      { label: '产品文档', value: 'product_docs' },
                      { label: '技术文档', value: 'tech_docs' },
                      { label: '用户手册', value: 'user_manual' },
                      { label: '常见问题', value: 'faq' },
                      { label: '内部知识库', value: 'internal_kb' }
                    ]}
                  />
                </>
              )}
            </Space>
            
            <Divider />
          </div>
          
          <div>
            <Title level={5}>上下文设置</Title>
            <Space direction="vertical" style={{ width: '100%' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <Text>保留上下文消息</Text>
                <Radio.Group defaultValue="medium">
                  <Radio.Button value="short">少量</Radio.Button>
                  <Radio.Button value="medium">中等</Radio.Button>
                  <Radio.Button value="long">大量</Radio.Button>
                </Radio.Group>
              </div>
              <Text type="secondary" style={{ fontSize: '12px' }}>
                决定AI回复时考虑的历史消息数量。消息越多，上下文理解越好，但会消耗更多Token。
              </Text>
            </Space>
          </div>
        </Space>
      </Drawer>
    );
  };

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
      <Card
        title={
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <span>AI对话</span>
            <Space>
              <Tooltip title="历史对话">
                <Button
                  icon={<HistoryOutlined />}
                  onClick={() => setHistoryDrawerVisible(true)}
                />
              </Tooltip>
              <Tooltip title="设置">
                <Button
                  icon={<SettingOutlined />}
                  onClick={() => setSettingsDrawerVisible(true)}
                />
              </Tooltip>
              <Tooltip title="清空对话">
                <Button
                  icon={<ClearOutlined />}
                  onClick={handleClearChat}
                />
              </Tooltip>
            </Space>
          </div>
        }
        bordered={false}
        style={{ 
          height: '100%', 
          display: 'flex', 
          flexDirection: 'column',
          borderRadius: 0
        }}
        bodyStyle={{ 
          flex: 1, 
          padding: '12px', 
          overflow: 'auto',
          display: 'flex',
          flexDirection: 'column'
        }}
      >
        <div style={{ flex: 1, overflow: 'auto', marginBottom: '16px' }}>
          {messages.length === 0 ? (
            <Empty 
              description={
                <div style={{ marginTop: '16px' }}>
                  <Text>开始一段新的对话吧</Text>
                  {/* 添加一些示例提示 */}
                  <div style={{ marginTop: '24px' }}>
                    <Text type="secondary" style={{ display: 'block', marginBottom: '12px' }}>示例问题:</Text>
                    <Space direction="vertical" style={{ width: '100%' }}>
                      {['请介绍一下你们的主要产品功能', '你们的系统支持私有化部署吗？', '如何开始使用知识库功能？', '产品的价格方案是怎样的？'].map((q, i) => (
                        <Card 
                          key={i} 
                          size="small" 
                          hoverable 
                          style={{ cursor: 'pointer' }}
                          onClick={() => setInputValue(q)}
                        >
                          {q}
                        </Card>
                      ))}
                    </Space>
                  </div>
                </div>
              }
              style={{ marginTop: '64px' }}
            />
          ) : (
            <List
              dataSource={messages}
              renderItem={renderMessage}
              style={{ overflow: 'auto' }}
            />
          )}
          {isTyping && (
            <div style={{ padding: '12px 24px', display: 'flex', alignItems: 'center', gap: '8px' }}>
              <LoadingOutlined style={{ fontSize: '16px' }} />
              <Text type="secondary">AI正在思考中...</Text>
            </div>
          )}
          <div ref={messagesEndRef} />
        </div>
        
        <div style={{ 
          display: 'flex', 
          flexDirection: 'column',
          backgroundColor: token.colorBgContainer,
          padding: '16px',
          borderRadius: '8px',
          boxShadow: '0 2px 8px rgba(0, 0, 0, 0.06)'
        }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '12px' }}>
            <Space>
              <Select 
                style={{ width: 180 }}
                placeholder="选择模型"
                value={selectedModel ? selectedModel.id : undefined}
                onChange={modelId => {
                  const model = llmModels.find(m => m.id === modelId);
                  if (model) {
                    setSelectedModel(model);
                  }
                }}
              >
                {llmModels.map(model => (
                  <Option key={model.id} value={model.id}>
                    <Tooltip title={`${model.name} - ${model.provider}`}>
                      <Space>
                        {model.isActive && <Badge status="success" />}
                        {model.name}
                      </Space>
                    </Tooltip>
                  </Option>
                ))}
              </Select>
              <Tooltip title={useKnowledgeBase ? "知识库增强已启用" : "知识库增强已禁用"}>
                <Button 
                  type={useKnowledgeBase ? "primary" : "default"}
                  icon={<DatabaseOutlined />}
                  onClick={() => handleKnowledgeBaseChange(!useKnowledgeBase)}
                >
                  知识库
                </Button>
              </Tooltip>
            </Space>
            <Space>
              <Upload
                fileList={uploadedFiles}
                onChange={({ fileList }) => setUploadedFiles(fileList)}
                multiple
                showUploadList={false}
              >
                <Tooltip title="上传附件">
                  <Button icon={<PaperClipOutlined />} />
                </Tooltip>
              </Upload>
              {uploadedFiles.length > 0 && (
                <Tag color="blue">
                  已选择{uploadedFiles.length}个文件
                </Tag>
              )}
            </Space>
          </div>
          
          <div style={{ display: 'flex', gap: '8px' }}>
            <Input.TextArea
              value={inputValue}
              onChange={e => setInputValue(e.target.value)}
              onKeyDown={handleKeyDown}
              placeholder="输入消息，Shift+Enter换行..."
              autoSize={{ minRows: 1, maxRows: 6 }}
              style={{ flex: 1 }}
            />
            <Button 
              type="primary" 
              icon={<SendOutlined />}
              onClick={handleSend}
              disabled={!inputValue.trim() || isTyping}
            >
              发送
            </Button>
          </div>
        </div>
      </Card>
      
      {renderHistoryDrawer()}
      {renderSettingsDrawer()}
    </div>
  );
};

export default ChatInterface; 